package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Component;
import ohos.multimodalinput.event.TouchEvent;

final class ComponentTouchObservable extends Observable<TouchEvent> {
    private final Component view;
    private final Predicate<? super TouchEvent> handled;

    ComponentTouchObservable(Component view, Predicate<? super TouchEvent> handled) {
        this.view = view;
        this.handled = handled;
    }

    @Override
    protected void subscribeActual(Observer<? super TouchEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, handled, observer);
        observer.onSubscribe(listener);
        view.setTouchEventListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements Component.TouchEventListener {
        private final Component view;
        private final Predicate<? super TouchEvent> handled;
        private final Observer<? super TouchEvent> observer;

        Listener(Component view, Predicate<? super TouchEvent> handled, Observer<? super TouchEvent> observer) {
            this.view = view;
            this.handled = handled;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setTouchEventListener(null);
        }

        @Override
        public boolean onTouchEvent(Component v, TouchEvent event) {
            if (!isDisposed()) {
                try {
                    if (handled.test(event)) {
                        observer.onNext(event);
                        return true;
                    }
                } catch (Throwable e) {
                    observer.onError(e);
                    dispose();
                }
            }
            return false;
        }
    }
}
